package com.kaochong.xcx.web.aspect;

import com.kaochong.xcx.cache.TokenCache;
import com.kaochong.xcx.enums.ResultEnum;
import com.kaochong.xcx.exception.AuthorizeException;
import com.kaochong.xcx.utils.RequestUtil;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;

/**
 * 登录校验拦截器
 *
 * @author han
 * @date 2018-05-01 16:49
 */
@Aspect
@Component
@Slf4j
public class AuthorizeAspect {
	
	@Autowired
	TokenCache tokenCache;
	
	@Pointcut("execution(public * com.kaochong.xcx.web.controller.*.*(..)) " +
			"&& !execution(public * com.kaochong.xcx.web.controller.WxOauthController.*(..)) " +
			"&& !execution(public * com.kaochong.xcx.web.controller.IndexController.banner(..)) " +
			"&& !execution(public * com.kaochong.xcx.web.controller.IndexController.nowTime(..)) " +
			"&& !execution(public * com.kaochong.xcx.web.controller.WordController.*(..)) ")
	public void verify() {
	}
	
	@Before("verify()")
	public void doVerify() {
		long req_begin = System.currentTimeMillis();
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		// 设置请求时间
		request.setAttribute("req_begin", req_begin);
		String token = request.getParameter("token");
		if (StringUtils.isBlank(token)) {
			throw new AuthorizeException(ResultEnum.PARAM_TOKEN_REQUIRED_ERROR);
		}
		
		CurrentUser user = tokenCache.getToken(token);
		if (user == null) {
			log.error("【登录拦截】redis中查不到token，token={}", token);
			throw new AuthorizeException(ResultEnum.TOKEN_IS_INVALID_ERROR);
		}
		UserContext.setUser(user);
	}
	
	@After("verify()")
	public void afterVerify() {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		// 获取开始请求时间
		Long req_begin = (Long) request.getAttribute("req_begin");
		Long req_end = System.currentTimeMillis();
		if (req_end - req_begin >= 3000) {
			log.warn("【请求时间大于3秒】：used time={},path={}", req_end - req_begin, RequestUtil.getRequestUrl(request));
		}
		UserContext.remove();
	}
}
